package com.shuangyu.controller;

import com.shuangyu.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${reggie.path}")
    private String filePath;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){

        //截取文件后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        //判断目录存不存在，不存在就创建一个
        File f = new File(filePath);
        if (!f.exists()){
            f.mkdirs();
        }

        //随机一个文件名字，防止名字重复覆盖文件
        String fileName = UUID.randomUUID().toString() + suffix;

        //将file文件转存到指定位置
        try {
            file.transferTo(new File(filePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success(fileName);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){

        //创建输入流和输出流
        FileInputStream fileInputStream = null;
        ServletOutputStream servletOutputStream = null;

        try {
            //通过输入流读取文件内容
            fileInputStream = new FileInputStream(new File(filePath + name));
            //通过输出流将文件写回浏览器
            servletOutputStream = response.getOutputStream();

            int len = 0;
            byte[] bytes = new byte[1024];

            while ((len = fileInputStream.read(bytes)) != -1){
                servletOutputStream.write(bytes, 0, len);
                servletOutputStream.flush();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                fileInputStream.close();
                servletOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }


        }


    }

}
